package com.example.mongodb1;

import com.example.mongodb1.entity.User;
import com.mongodb.client.result.UpdateResult;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.BasicQuery;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.data.mongodb.core.query.Update;

import java.util.List;

@SpringBootTest
public class Mongo1 {

    @Autowired
    private MongoTemplate mongoTemplate;


    @Test
    void createCollection(){
        boolean user = mongoTemplate.collectionExists(User.class);
        if(!user){
            mongoTemplate.createCollection(User.class);
        }

        System.out.println(user);
    }

    @Test
    void list(){
        List<User> all = mongoTemplate.findAll(User.class);
        System.out.println(all);
    }

    @Test
    void find2(){
        User one = mongoTemplate.findOne(new Query(), User.class);
        System.out.println(one);
    }

    @Test
    void find3(){
        Criteria criteria = Criteria.where("name").is("李四");
        Query query = new Query(criteria);

        User one = mongoTemplate.findOne(query, User.class);
        System.out.println(one);
    }

    @Test
    void update1(){
        Update update = new Update();
        update.inc("age",12);
        UpdateResult updateResult = mongoTemplate.updateFirst(new Query(), update, User.class);
//        mongoTemplate.up
        System.out.println(updateResult);
    }

    @Test
    void findByJson1(){
        String queryStr = "{name:'张三'}";
        Query query = new BasicQuery(queryStr);
        List<User> users = mongoTemplate.find(query, User.class);
        System.out.println(users);
        String queryStr2 = "{age:{$gt:20}}";

        Query query2 = new BasicQuery(queryStr2);
        List<User> users2 = mongoTemplate.find(query2, User.class);
        System.out.println(users2);
    }

    @Test
    void instert1(){
        User yu = new User(null, "yu", 12, null);
        User insert = mongoTemplate.insert(yu);

    }



}
